class FileLoadsManager {
    /**
     * 构造函数
     * @param {Object} options 配置选项
     */
    constructor(options = {}) {
        this.layui = layui;
        this.layer = layui.layer;
        this.form = layui.form;
        this.element = layui.element;
        
        // 默认配置
        this.config = {
            time: '',
            event: '',
            srcIp: '',
            srcPath: '',
            srcUsername: '',
            srcPassword: '',
            destIp: '',
            destPath: '',
            destUsername: '',
            destPassword: '',
            transferMode: 'scp-p2p', // scp-p2p 、scp-p2s 或 server
            ...options
        };
        
        // 事件回调
        this.callbacks = {
            onDownloadStart: null,
            onDownloadProgress: null,
            onDownloadCancel: null,
            onDownloadComplete: null,
            onDownloadError: null,
            onUploadStart: null,
            onUploadProgress: null,
            onUploadCancel: null,
            onUploadComplete: null,
            onUploadError: null,
        };

        this.currentTransfer = {
            fileName: '',
            totalSize: 0,
            transferredSize: 0,
            speed: 0,
            remainingTime: 0,
            progress: 0,
            status: 'pending', // pending, transferring, completed, failed, cancelled
        };
        
        this.init();
    }
    
    /**
     * 初始化
     */
    init() {
        if (window.SocketClient && window.SocketClient.socket) {
            this.socketEvent();
        }
        console.log('FileDownloadManager 初始化完成');
    }

    socketEvent(){
        //=========== socket监听事件 =========
        // 监听下载进度更新
        window.SocketClient.socket.on('download_recall', function(data) {
            console.log('下载召回:', data);
        });
        // 监听上传进度更新
        window.SocketClient.socket.on('upload_recall', function(data) {
            console.log('上传召回:', data);
        });
        // 监听传输取消回调事件
        window.SocketClient.socket.on('transfer_cancel_recall', function(data) {
            console.log('传输停止:', data);
        });
        // 监听传输进度列表
        window.SocketClient.socket.on('progress_list', (data) => {
            console.log('进度更新:', data);
            
            this.loadProgressList(data) 

            // var progress_num = data[0].percent
            // var progress = data[0].percent_str
            // var speed = data[0].speed_str
            // var remainingTime = data[0].eta_str
            // var transferredSize = data[0].sent_str
            // var totalSize = data[0].size_str
            // this.updateProgressDisplay(progress_num,progress, speed, remainingTime, transferredSize, totalSize);
        });
    }


    // 渲染传输选项：有三个按钮：传输列表、上传、下载，点击后弹出对应的弹窗
    renderTransferMenu() {
        // Todo
        var content = `
            <div style="padding: 20px; text-align: center;">
                <button type="button" class="layui-btn layui-btn-normal" style="margin: 10px;" id="transferList">传输列表</button>
                <button type="button" class="layui-btn layui-btn-warm" style="margin: 10px;" id="uploadForm">上传</button>
                <button type="button" class="layui-btn" style="margin: 10px;" id="downloadForm">下载</button>
            </div>
        `;
        
        layer.open({
            type: 1,
            title: '传输操作',
            content: content,
            area: ['500px', 'auto'],
            btn: ['关闭'],
            yes: function(index) {
                layer.close(index);
            },
            success: (layero, index) => {
                // 绑定按钮点击事件
                layero.find('#transferList').on('click', () => {
                    window.SocketClient.socket.emit('get_progress_list', {event: 'get_progress_list'});
                    this.renderTransferList(index);
                });
                layero.find('#uploadForm').on('click', () => {
                    this.renderUpload(index);
                });
                layero.find('#downloadForm').on('click', () => {
                    this.renderDownload(index);
                });
            }
        });
    }

    // 加载传输进度列表
    // loadProgressList(progress_list) {
    //     console.log('loadProgressList', progress_list);

    // }

    // 加载传输进度列表
    loadProgressList(progress_list) {
        console.log('loadProgressList', progress_list);
        // this.transferTasks = progress_list || [];
        
        // 如果弹窗已打开，更新内容
        const container = document.querySelector('.transfer-list-content');
        if (container) {
            container.innerHTML = this.generateTransferListContent(progress_list);
        }
    }


    // 生成列表内容
    generateTransferListContent(transferTasks=[]) {
        if (!transferTasks.length) {
            return '<div style="text-align: center; padding: 40px; color: #999;">暂无传输任务</div>';
        }
        
        let content = '';
        transferTasks.forEach((task) => {
            content += `
                <div style="margin-bottom: 15px; padding: 10px; border: 1px solid #eee;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                        <span>${task.destUsername}@${task.destIp}:${task.filename}</span>
                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" style="margin-left: 10px;" id="cancelTransfer_${task.id}">取消</button>
                    </div>
                    <div class="layui-progress" lay-filter="transferProgress">
                        <div class="layui-progress-bar" lay-percent="${task.percent_str || '0%'}"></div>
                    </div>
                    <div style="display: flex; justify-content: space-between; font-size: 12px; color: #666; margin-top: 5px;">
                        <span>${task.percent_str || '0%'} | ${task.sent_str}/${task.size_str} | 速度: ${task.speed_str} | 剩余: ${task.eta_str} | ${task.event==='download'?'下载':'上传'}</span>

                        <span style="color: ${task.status === '传输完成' ? 'green' : task.status === '传输失败' ? 'red' : 'blue'} ">${task.status}</span>
                    </div>
                </div>
            `;
        });

        // 更新进度条进度



        return content;
    }


    // 渲染传输列表弹窗
    renderTransferList(index) {
        
        const listContent = `<div style="padding: 20px; max-height: 400px; overflow-y: auto;" class="transfer-list-content">${this.generateTransferListContent()}</div>`;

        this.layer.open({
            type: 1,
            title: '传输列表',
            content: listContent,
            area: ['600px', '500px'],
            btn: ['关闭'],
            yes: function(index) {
                layer.close(index);
                window.SocketClient.socket.emit('stop_progress', {event: 'stop_progress'});
            },
            success: (layero, index) => {
                window.SocketClient.socket.emit('get_progress_list', {event: 'get_progress_list'});
                
            }
        });
        
        
    }

    // 渲染上传弹窗
    renderUpload(index) {
        this.layer.close(index);
        this.showTransferForm('上传', 'upload');
    }

    // 渲染下载弹窗
    renderDownload(index) {
        this.layer.close(index);
        this.showTransferForm('下载', 'download');
    }

    // 显示传输表单
    showTransferForm(title, type) {
        var formContent = `
            <form class="layui-form" lay-filter="transferForm" style="padding: 20px;">
                <div class="layui-form-item">
                    <label class="layui-form-label">传输方式</label>
                    <div class="layui-input-block">
                        <input type="radio" name="method" lay-filter="transferMode"  value="scp-p2s" title="scp至服务器" checked>
                        <input type="radio" name="method" lay-filter="transferMode"  value="scp-p2p" title="scp直传">
                        <input type="radio" name="method" lay-filter="transferMode"  value="server" title="服务器中转">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">源IP</label>
                    <div class="layui-input-block">
                        <input type="text" name="sourceIP" placeholder="请输入源IP地址" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">源地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="sourcePath" placeholder="请输入源文件/目录路径" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">目标IP</label>
                    <div class="layui-input-block">
                        <input type="text" name="targetIP" placeholder="请输入目标IP地址" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">目标地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="targetPath" placeholder="请输入目标文件/目录路径" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </form>
        `;
        
        layer.open({
            type: 1,
            title: title + '文件',
            content: formContent,
            area: ['600px', '400px'],
            btn: ['开始' + title, '取消'],
            yes: (index) => {

                // 获取表单数据
                var formData = this.form.val('transferForm');
                // console.log('表单数据:', formData);
                
                // 提交传输任务 
                this.submitTransferTask(type, formData);
                this.layer.close(index);
            },
            btn2: (index) => {
                this.layer.close(index);
            },
            success: () => {
                var selectedRowPath = window.DetailManager.getSelectedRowPath();

                if (selectedRowPath) {
                    // 填充表单数据
                    if (type === 'upload') {
                        setTimeout(() => {
                            var formData = this.form.val('transferForm');
                            var method = formData.method;
                            var sourceIP = ""
                            if (method === 'scp-p2s') {
                                sourceIP = "server"
                            }
                            this.form.val('transferForm', {
                                targetIP: window.getConfig()['host'],
                                targetPath: selectedRowPath,
                                sourceIP: sourceIP
                            });
                            this.toggleFormFields(['sourceIP'], true);
                        }, 50);
                    } else if (type === 'download') {
                        setTimeout(() => { 
                            var formData = this.form.val('transferForm');
                            var method = formData.method;
                            var targetIP = ""
                            if (method === 'scp-p2s') {
                                targetIP = "server"
                            }
                            this.form.val('transferForm', {
                                sourceIP: window.getConfig()['host'],
                                sourcePath: selectedRowPath,
                                targetIP: targetIP
                            });
                            this.toggleFormFields(['targetIP'], true);
                        }, 50);

                    }

                    // 绑定模式切换事件
                    this.form.on('radio(transferMode)', (data) => {
                        console.log('选择的模式:', data.value);
                        if (data.value === 'scp-p2s') {
                            // 禁用目标IP
                            if (type === 'upload') {
                                this.toggleFormFields(['targetIP','sourcePath','targetPath'], false);
                                this.toggleFormFields(['sourceIP'], true);
                                // 输入默认值
                                const input = document.querySelector(`input[name="sourceIP"]`);
                                if (input) {
                                    input.value = 'server';
                                }

                            } else if (type === 'download') {
                                this.toggleFormFields(['sourceIP','sourcePath','targetPath'], false);
                                this.toggleFormFields(['targetIP'], true);
                                // 输入默认值
                                const input = document.querySelector(`input[name="targetIP"]`);
                                if (input) {
                                    input.value = 'server';
                                }

                            }
                        } else if (data.value === 'scp-p2p') {
                            // 启用目标IP
                            this.toggleFormFields(['sourceIP','sourcePath','targetIP','targetPath'], false);
                        } else if (data.value === 'server') {
                            this.toggleFormFields(['sourceIP','sourcePath','targetIP','targetPath'], false);
                        }
                        

                    });

                }

            }
        });
    }


    toggleFormFields(fieldNames, disabled) {
        fieldNames.forEach(fieldName => {
            // const formItem = document.querySelector(`.layui-form-item[name="${fieldName}"]`);

            const input = document.querySelector(`input[name="${fieldName}"]`);
            if (input) {
                const formItem = input.closest('.layui-form-item');
                if (disabled) {
                    formItem.classList.add('layui-input-disabled');
                    input.disabled = true;
                } else {
                    formItem.classList.remove('layui-input-disabled');
                    input.disabled = false;
                }
            }
        });
    }


     // 提交传输任务
    submitTransferTask(type, formData) {
        var taskData = {};
        if (type === 'upload') {
            taskData = {
                event: type, // 'upload' or 'download'
                time: new Date().getTime(),
                method: formData.method, // 'scp-p2p'、'scp-p2s' or 'server'
                sourceIP: formData.sourceIP,
                sourcePath: formData.sourcePath,
                sourcePort: "22",
                sourceUsername: '',
                sourcePassword: '',
                targetIP: formData.targetIP,
                targetPath: formData.targetPath,
                targetPort: window.getConfig()['port'],
                targetUsername: window.getConfig()['username'],
                targetPassword: window.getConfig()['password'],
            };
        }
        if (type === 'download') {
            taskData = {
                event: type, // 'upload' or 'download'
                time: new Date().getTime(),
                method: formData.method, // 'scp-p2p'、'scp-p2s' or 'server'
                sourceIP: formData.sourceIP,
                sourcePath: formData.sourcePath,
                sourcePort: window.getConfig()['port'],
                sourceUsername: window.getConfig()['username'],
                sourcePassword: window.getConfig()['password'],
                targetIP: formData.targetIP,
                targetPath: formData.targetPath,
                targetPort: '22',
                targetUsername: '',
                targetPassword: '',
            };
        }
        
        console.log('提交传输任务:', taskData);
        
        // 发送到服务器
        window.SocketClient.socket.emit('start_transfer', taskData);
        
        layer.msg('传输任务已提交', {icon: 1});
    }

}


window.FileLoadsManager = new FileLoadsManager();